package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dto.WmUserDto;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmUserDto dto) {
       //检查数据
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

       //查询数据库
        LambdaQueryWrapper<WmUser> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getName,dto.getName());
        WmUser wmUser = getOne(wrapper);
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名不存在");
        }
        //判断密码是否正确
        String encode = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        //String encode = MD5Utils.encode(dto.getPassword() + wmUser.getSalt());
        if (encode.equals(wmUser.getPassword())){
            String token = AppJwtUtil.getToken(wmUser.getId().longValue());
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            wmUser.setPassword("");
            wmUser.setSalt("");
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }
}
